package com.wormpex.data.root.service.impl;

import com.wormpex.api.json.JsonUtil;
import com.wormpex.data.root.dao.FailedTransmitMessageDao;
import com.wormpex.data.root.model.bean.FailedTransmitMessage;
import com.wormpex.data.root.model.bean.FromToEntry;
import com.wormpex.data.root.service.KafkaProducerService;
import com.wormpex.data.root.service.WmqTransmitKafkaService;
import com.wormpex.data.root.service.FromToMappingService;
import com.wormpex.inf.wmq.api.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * Created by ouryousa on 2017/8/17.
 */

@Service
public class WmqTransmitKafkaServiceImpl implements WmqTransmitKafkaService {

    @Autowired
    private FromToMappingService fromToMappingServiceImpl;

    @Autowired
    private KafkaProducerService kafkaProducerServiceImpl;

    @Autowired
    private FailedTransmitMessageDao failedTransmitMessageDao;

    @Value("kafka.topic.name")
    String defalutTopicName;

    /**
     * 转发Wmq中接受到的消息
     * @param message
     * @return
     */
    @Override
    public boolean transmit(Message message) {
        String topic = message.getTopic();
        Map<String ,String> attrs = message.getAttrs();
        String value = JsonUtil.of(attrs);
        if(value == null){
            return true;
        }
        List<FromToEntry> fromToEntries = fromToMappingServiceImpl.getWmqKafkaEntries(topic);
        for (FromToEntry fromToEntry : fromToEntries) {
            if(!transmit1(fromToEntry.getToTopicName(), value)){
                FailedTransmitMessage failedTransmitMessage = new FailedTransmitMessage();
                failedTransmitMessage.setMessage(value);
                failedTransmitMessage.setFromSourceType("Wmq");
                failedTransmitMessage.setToSourceType("Kafka");
                failedTransmitMessage.setFromTopicName(topic);
                failedTransmitMessage.setToTopicName(fromToEntry.getToTopicName());
                failedTransmitMessageDao.insertSelective(failedTransmitMessage);
            }
        }
        return true;

    }

    /**
     * 转发单条消息
     * @param toTopicName
     * @param value
     * @return
     */
    @Override
    public boolean transmit1(String toTopicName, String value){
        int retryTimes = 5;
        while(0 != retryTimes){
            if(kafkaProducerServiceImpl.sendMessage(toTopicName, value)){
                return true;
            }
            retryTimes--;
        }
        return false;
    }
}
